let mongoose = require('mongoose');
const weChat=require('../../util/wechat');
const ValidTime = {
    world : 180000,
    private: 7*24*60*60*1000
}
let schema = new mongoose.Schema({
},{versionKey:false});

schema.methods = {
    //发送消息
    async send(options={self:null,channel:0,type:0,content:''}){
        let Chat = mongoose.models['Chat'];
        if(options.channel == 'world'&& !options.self.bag.hasItem(201)){
            throw  new Error('喇叭不足')
        }

        let checkResult=await weChat.msgSecCheck(options.content);
        if(!checkResult){
            throw new Error('根据政策法规，消息包含非法字符！');
        }

        let msgs = await Chat.findOrCreate(options.channel);
        if(msgs.messages.length>=msgs.maxMessageCount){
            msgs.messages.shift();
        }



        // console.log(options.content);
        msgs.messages.push({
            userId:options.self._id,
            type:options.type,
            content:options.content,
            time:new Date().getTime()
        });

        if(options.channel == 'world'){
            options.self.bag.reduceItem(201,1);
        }

        await options.self.save();
        await msgs.save();
    },
    //将消息转成带昵称，头像的方式。
    async _messagesToResult(messages){
        let userIds=[];
        for(let i=0;i<messages.length;i++){
            userIds.push(messages[i].userId);
        }
        let GameUserModel=mongoose.models['GameUser'];
        let gameUserList=await GameUserModel.find({_id:{$in:userIds}});
        let result=[];
        for(let i=0;i<messages.length;i++){
            let gameUser= await gameUserList.find(item=>{return item._id==messages[i].userId});
            if(!gameUser){
                continue
            }
            let obj={};
            Object.assign(obj,{
                content:messages[i].content,
                time:messages[i].time,
                _id:messages[i].userId,
                type:messages[i].type
            },{
                nickname:gameUser.nickname,
                headImgUrl:gameUser.headImgUrl,
                level : gameUser.ppt.level,
                sex:gameUser.sex
            });
            result.push(obj);
        }
        return result;
    },
    async deleteMsg(msgs,channel){
        if(channel.indexOf('world')>=0){
            if(msgs.messages.length > 50){
                msgs.messages.splice(0,msgs.messages.length-50);
            }
        }
        let nowTime = Date.now();
        let len = msgs.messages.length;
        let i=0;
        while(i<msgs.messages.length){
            let msg = msgs.messages[i];
            let dt = nowTime-msg.time;
                if(dt >= ValidTime.private){
                    msgs.messages.splice(i,1);
                    continue
                }
            i++
        }
        if(len!=i){
            await msgs.save();
        }
    },
    //获取聊天记录
    async list(options={firstTime:9539411549961,rows:50}){
        let rows=options.rows;
        let firstTime=options.firstTime;
        let Chat = mongoose.models['Chat']
        let msgs = await Chat.findOrCreate(options.channel);
        if(!rows){
            rows=10;
        }
        if(!firstTime){
            firstTime=9539411549961;
        }
        if(options.channel.indexOf('private')>=0){
            let otherId =  options.channel.substring(options.channel.lastIndexOf('_')+1);
            let idx = options.self.id == parseInt(otherId) ? 1: 0;
            let tick = [msgs.lastGetTick[0],msgs.lastGetTick[1]]
            tick[idx] = Date.now()
            msgs.lastGetTick = tick
            await msgs.save();
        }
        await this.deleteMsg(msgs,options.channel);
        let messages=msgs.messages.filter(item=>{return item.time<firstTime});
        if(msgs.messages.length>rows){
            messages=messages.slice(-rows);
        }
        let msg = await this._messagesToResult(messages)
        return {messages:msg,horn:options.self.bag.getCount(201)}
    },
    //轮询获取最新消息
    async newTest(options={lastTime:0}){
        let ChatModel = mongoose.models['Chat'];
        let time = new Date().getTime()
        let msgs = await  ChatModel.findOrCreate(options.channel);
        if(options.channel.indexOf('private')>=0){
            let otherId =  options.channel.substring(options.channel.lastIndexOf('_')+1);
            let idx = options.self.id == parseInt(otherId) ? 1: 0;
            let tick = [msgs.lastGetTick[0],msgs.lastGetTick[1]]
            tick[idx] = Date.now()
            msgs.lastGetTick = tick
            await msgs.save();
        }
        let messages=msgs.messages.filter(item=>{return item.time>options.lastTime});
        return await this._messagesToResult(messages);
    }
}

module.exports=schema;